<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <script>
        window.onload = function () {
            initData(1, 10);
        }
        /*function initData(page,size) {
            $.ajax({
                url:'allGoods',
                type:'GET',
                data:{
                    'page':page,
                    'size':size
                },
                dataType:'text',
                success:function(res) {
                    console.log("分页数据："+res)
                    let data = JSON.parse(res); //转换为JSON格式，原因：用户想要使用对象.属性格式引用数据
                    console.log("JSON数据："+data)
                    if (data.code == 200){
                        console.log("分页数据："+res)
                        $('#tb').empty();
                        $('#tdbar').empty();
                        console.log(">>>>>>>>>>>>>>>>>>")
                        let data_temp =data.data
                        console.log(data_temp)
                        for (let i = 0; i < data_temp.length; i++){
                            $("<tr><td>"+data_temp[i].id+"</td>" +
                                "<td>"+data_temp[i].title+"</td>" +
                                "<td>"+data_temp[i].price+"</td>" +
                                "<td>"+data_temp[i].descr+"</td>" +
                                "<td><img src='"+data_temp[i].img+"' width='50' height='50'/></td>" +
                                "<td>"+data_temp[i].state+"</td>" +
                                "<td>"+data_temp[i].mid+"</td>" +
                                "<td><button class='btn btn-primary'>编辑</button><button class='btn btn-danger'>删除</button></td>" +
                                "</tr>").appendTo('#tb');
                        }
                    }
                },
                error:function(xhr, status, error) {
                    console.error('请求失败:', status, error);
                    alert('请求商品列表失败，请检查网络或联系管理员');
                }


            })
        }
*/

        function initData(page,size) {
            $.ajax({
                url:'allGoods',
                type:'GET',
                data: {
                    'page': page,
                    'size': size
                },
                //为什么转换为JSON格式，原因：用户想要使用对象.属性格式引用数据
                dataType:'json', // 直接接收JSON格式
                success: function(data) { // data已经是解析后的数组
                    console.log("完整响应数据:", data);
                    $('#tb').empty(); // 清空表格
                    $('#tdbar').empty();

                    // 直接遍历数组
                    data.forEach(function(item) {
                        const row = `
                        <tr>
                            <td><input type="checkbox" value="${item.id}" name="chk"/></td>
                            <td>${item.id}</td>
                            <td>${item.title}</td>
                            <!-- 保留两位小数 -->
                            <td>${item.price.toFixed(2)}</td>
                            <td>${item.descr}</td>
                            <td><img src="${item.img}" width="50" height="50" alt="商品图"></td>
                            <td>${item.state === 0 ? '可销售' : '不可销售'}</td>
                            <td>${item.mid}</td>
                            <td>
                                <button class="btn btn-primary" onclick="loadEditForm(${item.id})">编辑</button>
                                <button class="btn btn-danger" onclick="delRow(${item.id},${page})">删除</button>
                            </td>
                            </tr>`;
                        $('#tb').append(row);
                    });
                    let validPage = data.length > 0 ? page : page - 1;
                    const isLastPage = data.length < size;  // 判断是否是最后一页
                    const lastPage = isLastPage ? validPage : 10;  // 动态尾页计算
                    const prevPage = Math.max(validPage - 1, 1);
                    const nextPage = validPage + 1;
                    // 生成分页按钮
                    $(`<button class="btn btn-primary" onclick="initData(1,10)">首页</button>&nbsp;&nbsp;
                       <button class="btn btn-primary" onclick="initData(${prevPage},10)">上一页</button>&nbsp;&nbsp;
                       <button class="btn btn-primary" ${isLastPage ? 'disabled' : ''} onclick="initData(${nextPage},10)">下一页</button>&nbsp;&nbsp;
                       <button class="btn btn-primary" onclick="initData(${lastPage},10)">尾页</button>`)
                        .appendTo("#tdbar");
                    // 自动纠正无效请求
                    if(data.length === 0 && page > 1) {
                        initData(prevPage, size);  // 自动跳转上一页
                    }
                },
                error: function(xhr, status, error) {
                    console.error('请求失败:', status, error);
                    alert('请求商品列表失败，请检查网络或联系管理员');
                }
            });
        }
        //逻辑删除商品功能
        function delRow(id,page) {
            let anw=window.confirm("你确定要删除这条数据？")
            console.log(anw)

            if (anw){
                console.log(id,page);
                $.ajax({
                    url: "delGoods",
                    type: "POST",
                    data: {
                        id:id,
                        page:page
                    },
                    dataType: 'text',
                    success:function (res){
                        if ("Y"){
                            alert("数据删除成功")
                            initData(page,10)
                        }else{
                            alert("系统异常或数据已被删除")
                        }
                    }
                })
            }else {
                return ;    //程序停止执行
            }

        }

        // 商品数据加载函数
        function loadEditForm(id) {
            $.ajax({
                url: "goodsDetail",
                type: "GET",
                data: {
                    id:id,
                    title:null,
                    price:null,
                    descr: null,
                    img:null,
                    state:null,
                    mid:null
                },
                dataType: 'json',
                success:function (res){
                    console.log(res)
                    if (res.code === 200) {
                        const item = res.data;
                        // 填充表单数据
                        $('#editModal input[name="id"]').val(item.id);
                        $('#editModal input[name="title"]').val(item.title);
                        $('#editModal input[name="price"]').val(item.price.toFixed(2)); // 保留两位小数
                        $('#editModal textarea[name="descr"]').val(item.descr);
                        $('#editModal input[name="img"]').val(item.img);
                        $('#editModal select[name="state"]').val(item.state.toString());
                        $('#editModal input[name="mid"]').val(item.mid);

                        // 图片预览
                        $('#previewImg').attr('src', item.img).css({
                            'max-width': '100%',
                            'height': 'auto'
                        });
                        // 显示模态框
                        $('#editModal').modal('show');
                    } else {
                        alert("数据加载失败: " + res.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('请求失败:', status, error);
                    alert('商品详情加载失败，请检查网络连接');
                }
            })
        }

    </script>
</head>

<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">商品搜索：</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

                <form class="navbar-form navbar-left">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="请输入商品名称" oninput="queryData(this.value)">
                    </div>
                    <button class="btn btn-danger" style="margin-left: 50px" onclick="delBatch()">批量删除</button>
                </form>

            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
    <script>
        //批量删除
        function delBatch(){
            let chks=document.getElementsByName('chk')
            for (let i=0;i<chks.length;i++){
                if(chks[i].checked){
                    console.log(">>>>>>",chks[i].value)
                }
            }
        }
        //反转
        function reSelectAll(){
            let chkval=document.getElementById('checkValue')
            console.log(chkval.checked)
            if (chkval.checked){
                let chks=document.getElementsByName('chk')
                for (let i=0;i<chks.length;i++){
                    // chks[i].checked=chks[i].checked?false:true
                    chks[i].checked=!chks[i].checked
                }
            }else{
                let chks=document.getElementsByName('chk')
                for (let i=0;i<chks.length;i++){
                    // chks[i].checked=chks[i].checked?false:true
                    chks[i].checked=!chks[i].checked
                }
            }
        }
    </script>
    <table class="table table-bordered table-striped table-hover">
        <thead>
            <th>
<!--                <button >反选</button>-->
                <input type="checkbox" value="0"  id="checkValue" onclick="reSelectAll()"/>
            </th>
            <th>#</th>
            <th>商品名称</th>
            <th>商品价格</th>
            <th>商品描述</th>
            <th>商品图片</th>
            <th>状态</th>
            <th>商家</th>
            <th>操作</th>
        </thead>
        <tbody id="tb">

        </tbody>
        <tfoot>
        <td colspan="11" style="text-align: center;" id="tdbar">

        </td>
        </tfoot>
    </table>


    <!-- 编辑模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <!-- 模态框头部 -->
                <div class="modal-header bg-primary">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title text-white">编辑商品信息</h4>
                </div>

                <!-- 模态框主体 -->
                <div class="modal-body">
                    <form id="editForm" class="form-horizontal">
                        <!-- 两列布局 -->
                        <div class="row">
                            <!-- 左列 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">商品ID</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" name="id" readonly>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">商品名称</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" name="title" required>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">价格</label>
                                    <div class="col-sm-9">
                                        <div class="input-group">
                                            <span class="input-group-addon">¥</span>
                                            <input type="number" class="form-control" name="price" step="0.01" min="0" required>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 右列 -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="col-sm-3 control-label">状态</label>
                                    <div class="col-sm-9">
                                        <select class="form-control" name="state">
                                            <option value="0">可销售</option>
                                            <option value="1">不可销售</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">商家ID</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" name="mid" required>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-3 control-label">图片URL</label>
                                    <div class="col-sm-9">
                                        <input type="url" class="form-control" name="img" pattern="https?://.+">
                                        <div class="thumbnail" style="margin-top:10px">
                                            <img id="previewImg" src="#" alt="图片预览" style="max-height:100px">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 全宽字段 -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品描述</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" name="descr" rows="3" maxlength="200"></textarea>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 模态框底部 -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitEditForm()">保存更改</button>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* 增强样式 */
        .modal-content {
            border-radius: 0;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .form-group label {
            font-weight: 600;
            color: #555;
        }
        .thumbnail {
            padding: 5px;
            border: 1px solid #ddd;
        }
    </style>

</body>
</html>
<script>
    function queryData(keywords){
        if (keywords==''){
            initData(1,10)
        }
        console.log("keywords："+keywords);
        $.ajax({
            url:"queryByCondition",
            type:"GET",
            data:{
                keywords:keywords
            },
            dataType:"text",
            success:function (res){
                console.log("查询的数据：",res)
                let data=JSON.parse(res)
                if (data.code==200){
                    console.log(">>>>>>>>>>>：")
                    $('#tb').empty();
                    $('#tdbar').empty();
                    console.log(">>>>>>>>>>>>>>>>>>")
                    let data_temp =data.data

                    console.log(data_temp)
                    for (let i = 0; i < data_temp.length; i++){
                        $("<tr><td>"+data_temp[i].id+"</td>" +
                            "<td>"+data_temp[i].title+"</td>" +
                            "<td>"+data_temp[i].price+"</td>" +
                            "<td>"+data_temp[i].descr+"</td>" +
                            "<td><img src='"+data_temp[i].img+"' width='50' height='50'/></td>" +
                            "<td>"+data_temp[i].state+"</td>" +
                            "<td>"+data_temp[i].mid+"</td>" +
                            "<td><button class='btn btn-primary'>编辑</button><button class='btn btn-danger'>删除</button></td>" +
                            "</tr>").appendTo('#tb');
                    }

                }
            }
        })
    }

    // 编辑表单提交函数
    function submitEditForm() {
        // 获取表单数据
        const formData = {
            id: $('#editModal input[name="id"]').val(),
            title: $('#editModal input[name="title"]').val().trim(),
            // price: parseFloat($('#editModal input[name="price"]').val()).toFixed(2),
            price: parseFloat($('#editModal input[name="price"]').val()),
            descr: $('#editModal textarea[name="descr"]').val().trim(),
            img: $('#editModal input[name="img"]').val().trim(),
            state: parseInt($('#editModal select[name="state"]').val()),
            mid: $('#editModal input[name="mid"]').val().trim()
        };
        console.log('提交数据:', JSON.stringify(formData, null, 2));
        // 前端验证
        if (!formData.title) {
            alert('商品名称不能为空');
            return;
        }
        if (isNaN(formData.price) || formData.price <= 0) {
            alert('请输入有效的价格');
            return;
        }
        $.ajax({
            url: 'updateGoods',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            dataType: 'json',
            beforeSend: function() {
                // 禁用提交按钮防止重复提交
                $('#editModal .btn-primary').prop('disabled', true).html('保存中...');
            },
            success: function(res) {
                console.log(res)
                if (res.code === 200) {
                    alert('修改成功');
                    $('#editModal').modal('hide');
                    // 刷新当前页数据
                    const currentPage = parseInt($('#tdbar button:not(:disabled)').filter(function() {
                        return $(this).text() === "下一页";
                    }).attr('onclick').match(/\d+/)[0]) - 1 || 1;
                    initData(currentPage, 10);
                } else {
                    alert('修改失败: ' + res.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('请求失败:', status, error);
                alert('保存失败，请检查网络连接');
            },
            complete: function() {
                // 恢复按钮状态
                $('#editModal .btn-primary').prop('disabled', false).html('保存更改');
            }
        });
    }

    // 图片URL输入实时预览（追加到页面脚本）
    $('#editModal input[name="img"]').on('input', function() {
        const newUrl = $(this).val();
        $('#previewImg').attr('src', newUrl).css({
            'max-width': '100%',
            'height': 'auto'
        });
    });


</script>


